<?php
/**
 * Created by PhpStorm.
 * User: wangxiaodan
 * Date: 2017/5/16
 * Time: 下午5:27
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Children;
use App\Models\Classes;
use App\Models\ClassesLogs;
use App\Models\Consume;
use App\Models\PrePaidCard;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ClassesController extends Controller
{
    private $week;
    private $today;

    public function __construct()
    {
        $this->week = Carbon::now()->weekOfYear;
        $this->today = Carbon::today();
    }

    public function index(){
        $classes = DB::table('classes as a')
            ->join('teachers as b', 'a.teacher_id', '=', 'b.teacher_id')
            ->select('*', 'a.id as class_id', 'b.nice_name as teacher_name')
            ->orderBy('a.weekday')
            ->orderBy('a.class_time')
            ->get();
        $children = Children::where("classes_id", "<>", null)->get();
        foreach ($classes as $class){
            $class->children = array();
            foreach ($children as $child){
                if ($class->id == $child->classes_id){
                    $class->children[] = array('id' => $child->id, 'name' => $child->name);
                }
            }
        }
        return view('admin.classes.index', ['classes' => $classes, 'week' => $this->week]);
    }

    public function show($id){
        $class = DB::table('classes as a')
            ->join('teachers as b', 'a.teacher_id', '=', 'b.teacher_id')
            ->select('*', 'a.id as class_id', 'b.nice_name as teacher_name')
            ->where('a.id', '=', $id)
            ->first();
        $course = DB::table('course_lib as a')
            ->join('course_subject as b', 'a.subject_id', '=', 'b.subject_id')
            ->where([["b.course_age", '=', $class->course_age],["a.week", '=',$this->week]])
            ->select('*', 'a.week as week', 'b.course_age as age')
            ->first();
        if (!$course){
            return view('errors.redirect',['message' => '请先录入课程','url' => 'admin/classes']);
        }
        $children = Children::where('classes_id', $id)->get();
        if ($children->isEmpty()){
            $children = null;
        }else{
            $consumes = DB::table('consumes as a')
                ->join('classes_logs as b', 'a.classes_log_id', '=', 'b.id')
                ->select('child_id', 'a.created_at as created_at')
                ->where([['b.classes_id', $id], ['b.week', $this->week]])
                ->get();
            if($consumes){
                foreach ($children as &$child){
                    foreach ($consumes as $consume){
                        if ($child->id == $consume->child_id){
                            $child->created_time = $consume->created_at;
                        }
                    }
                }
            }

        }
        return view('admin.classes.show', compact('class', 'children', 'course'));
    }

    public function create(){
        return view('admin.classes.create');
    }

    public function store(Request $request){
        $data = $request->all();
        $data['class_time'] = Carbon::parse($data['class_time']);
        $result = Classes::create($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/classes')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function edit($id){
        $classes = DB::table('classes as c')
            ->join('teachers as t', 'c.teacher_id', '=', 't.teacher_id')
            ->find($id);
        return view('admin.classes.edit', compact('classes'));
    }

    public function update(Request $request, $id){
        $classes = Classes::findOrFail($id);
        $result = $classes->update($request->all());
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/classes')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $classes = Classes::findOrFail($id);
        Children::where("classes_id", $id)->update(['classes_id' => null]);
        if ($classes->delete()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }

    public function sign($class_id, $child_id, $course_id, $class_date=null){
        //查询课表
        $class = Classes::findOrFail($class_id);
        //查询课程信息
        $course = DB::table('course_lib as a')
            ->join('course_subject as b', 'a.subject_id', '=', 'b.subject_id')
            ->where('a.id', $course_id)
            ->first();

        //判断课程日期
        if ($class_date == null){
            if ($this->today->weekOfYear == $course->week){
                $day_num = $this->today->dayOfWeek - $class->weekday;
                if ($day_num >= 0){
                    $class_date = $this->today->subDays($day_num); //subDays表示减去几天
                }else{
                    exit(json_encode(array('code'=>0, 'msg'=>'签到时间超前')));
                }
            }else{
                exit(json_encode(array('code'=>0, 'msg'=>'签到课程不在本周，请联系管理员')));
            }
        }else{
            $this->today = Carbon::parse($class_date);
            $this->week = $this->today->weekOfYear;
        }

        //判断这个学生是否在这节课签到了
        //先查询这节课是否已经有人签过了
        $classes_log = ClassesLogs::where([['classes_id', $class_id], ['year', $this->today->year], ['week', $class_date->weekOfYear]])->first();
        if ($classes_log){
            //如果有人签过了，判断改名学生是否签过了
            $signed = Consume::where([['classes_log_id', $classes_log->id], ['child_id', $child_id]])->first();
        }else{
            //如果这节课没有人签过，则创建这节课的上课记录，并将该名学生这节课的上课记录标记为空
            $signed = false;
            $classes_log = ClassesLogs::create([
                'year'       => $this->today->year,
                'week'       => $this->week,
                'classes_id' => $class_id,
                'class_date' => $class_date,
                'class_time' => $class->class_time,
                'course_name'=> $course->name,
                'course_age' => $class->course_age,
                'teacher_id' => $class->teacher_id,
                'class_hour' => $course->class_hour,
            ]);
        }
        if ($signed){
            exit(json_encode(array('code'=>0, 'msg'=>'该名学生已经签到')));
        };

        //判断储值卡
        $card = PrePaidCard::where([['child_id', $child_id], ['status', 1]])->first();
        if(!$card){
            exit(json_encode(array('code'=>0, 'msg'=>'没有可用的储值卡')));
        }

        //判断该学生所有可用的课时数是否够用
        $card_all_hour = $card = PrePaidCard::where([['child_id', $child_id], ['status', 1]])->sum('remainder_class_hour');
        if ($course->class_hour > $card_all_hour){
            exit(json_encode(array('code'=>0, 'msg'=>'储值卡余额不足，请先充值')));
        }

        //计算扣款并更新储值卡信息
        $value = $this->calConsume($child_id, $course->class_hour);
        if ($value === false){
            exit(json_encode(array('code'=>0, 'msg'=>$value)));
        }

        $result = Consume::create([
            'classes_log_id' => $classes_log->id,
            'child_id'   => $child_id,
            'value'      => $value,
        ]);
        if ($result) {
            $msg = '签到成功';
        }else{
            $msg = '签到失败，请联系管理员';
        }
        exit(json_encode(array('code'=>1, 'msg'=>$msg, 'url'=>'/admin/classes/'.$class_id)));
    }

    private function calConsume($child_id, $course_class_hour){
        $value = 0;
        $card_all = $card = PrePaidCard::where([['child_id', $child_id], ['status', 1]])->get();
        for ($i=0; $i<=count($card_all); $i++){
            $card_all[$i]->remainder_class_hour = $card_all[$i]->remainder_class_hour - $course_class_hour;
            $class_value = $card_all[$i]->unit_price * $course_class_hour;

            if ($card_all[$i]->remainder_class_hour > 0) {
                $card_all[$i]->remainder_value = $card_all[$i]->remainder_value - abs($class_value);
            }elseif ($card_all[$i]->remainder_class_hour  == 0){
                $card_all[$i]->remainder_value = 0;
                $card_all[$i]->status = 0;
            }else{
                //这张卡上扣减的余额数
                $class_value = ($card_all[$i]->remainder_class_hour + $course_class_hour)*$card_all[$i]->unit_price;
                //剩余没扣的课时数
                $course_class_hour = abs($card_all[$i]->remainder_class_hour);
                //将这张卡余额减为0，并注销
                $card_all[$i]->remainder_class_hour = 0;
                $card_all[$i]->remainder_value = 0;
                $card_all[$i]->status = 0;
                $card_all[$i]->save();


                //累计上一张卡和这张卡被扣除的金额
                $value += abs($class_value);
                continue;
            }
            $value += abs($class_value);
            if ($result = $card_all[$i]->save()) {

                break;
            }else{
                return false;
            }
        }
        return $value;
    }

    public function retroactive($class, $child, $age, $weekday, $week){
        //查询课程信息
        $course = DB::table('course_lib as a')
            ->join('course_subject as b', 'a.subject_id', '=', 'b.subject_id')
            ->where([
                ['b.course_age', '=', $age],
                ['a.week', '=', $week],
            ])
            ->first();
        $class_date = $this->findDay($weekday, $week);
        $this->sign($class, $child, $course->id, $class_date);
    }

    private function findDay($weekday, $week){
        $date = Carbon::create(2017, 1, 1, 0, 0, 0);
        $day_num = ($week - 1)*7 + $weekday;
        return $date->addDays($day_num);
    }

}